import { ReactElement, useEffect, useRef } from 'react'
import { Modal, Form, FormInstance, message } from 'antd'
import UnitNumberInput from '@components/unitNumberInput'
import { WorkPerformanceSchema } from '@src/components/schema/performanceSchema'
import { awaitWrap } from '@src/assets/js/tool'
import { updateCountRequest } from './ajax'

const { Item } = Form

async function submitHandle (performanceid: string, work: WorkPerformanceSchema | null, count: number, hide: () => void, refreshData: () => void): Promise<void> {
  if (work === null) {
    return undefined
  }
  const h = message.loading('提交中', 120)
  const [e] = await awaitWrap(updateCountRequest(performanceid, work.accountid, count))
  h()
  if (e === null) {
    message.success('更新成功').then(null, null)
    hide()
    refreshData()
  }
}

interface Props {
  performanceid: string
  work: WorkPerformanceSchema | null
  visible: boolean
  data: number
  hide: () => void
  refreshData: () => void
}

function Main ({ performanceid, visible, data, work, hide, refreshData }: Props): ReactElement {
  const formRef = useRef<FormInstance>(null)
  useEffect(() => {
    const c = formRef.current
    if (c !== null && typeof data === 'number' && visible) {
      c.setFieldsValue({ accepter_advise_count: data })
    }
  }, [visible, data, formRef])
  useEffect(() => {
    const c = formRef.current
    if (!visible && c !== null) {
      c.resetFields()
    }
  }, [visible, formRef])
  return (
    <Modal title='编辑咨询次数' visible={visible} onCancel={hide} onOk={() => formRef.current?.submit()}>
      <Form ref={formRef} onFinish={async d => await submitHandle(performanceid, work, d.accepter_advise_count as number, hide, refreshData)}>
        <Item label='咨询次数' name='accepter_advise_count'>
          <UnitNumberInput min={0} />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
